#!/bin/bash
# 此脚本用来编译安装FLye-2.9软件
# Flye-2.9软件介绍
#   Flye是用于单分子组装数据的denovo基因组装的软件，输入是原始的PacBio或者ONT的序列文件，
#   输出是polished的contig。Flye可用于各种数据集，从小的细菌到大的哺乳动物，并且有针对微生物组装的模式。
#  Usage:
#     bash /path/to/build.sh /path/to/build /path/to/install
# 使用build.sh 脚本样例 bash /path/to/build.sh /path/to/build /path/to/install
# 使用build.sh 需要root权限或者sudo权限,否则无法安装依赖
#
##############################################################

source "$(
  cd "$(dirname "$0")" || exit 1
  pwd
)/common.sh"

function write_flye_run() {
  cat >"$1/flye-2.9-hpc/run.sh" <<EOF
#!/bin/bash
yum -y install sudo
sudo yum install -y m4 systemd-devel automake autoconf libtool make time patch zlib-devel zlib bc wget environment-modules tar gcc-c++ \\
libatomic python python2-setuptools 
source /etc/profile &> /dev/null
current_dir="\$(cd "\$(dirname "\${BASH_SOURCE[0]}")" && pwd -P)"
for f in "\${current_dir}"/*; do
  if [[ -d "\${f}" && -f "\$(ls "\${f}"/*modulefiles 2>&1)" ]]; then
    module use "\${f}" && module load "\${f}"/*modulefiles
  fi
done
echo -e "\033[1;32;1mFlye environment initialization completed.\033[0m"
EOF

  chmod +x "$1"/flye-2.9-hpc/run.sh
}

function install_bisheng() {
  bash "$1"/bisheng-compiler-2.1.0.sh "$2" "$3"
  module use "$3"/bisheng-compiler-2.1.0
  module load "$3"/bisheng-compiler-2.1.0/bisheng_modulefiles
}

function install_flye() {
  bash "$4"/flye-2.9.sh "$1" "$2"
  mkdir -p "$3"/flye-2.9-hpc && cp -r "$2"/* "$3"/flye-2.9-hpc/
}

function tar_pkg() {
  echo "# 正在打包FLYE文件 路径为$1"
  cd "$1" && tar zcfP flye-2.9-hpc.tar.gz flye-2.9-hpc
  echo -e "\033[1;32;1m# FLYE已经打包成功 文件路径为$1/flye-2.9-hpc.tar.gz\033[0m"
}

function install_development() {
  yum -y install sudo
  sudo yum install -y m4 systemd-devel automake autoconf libtool make time patch environment-modules zlib-devel zlib bc gcc-c++
  source /etc/profile
  module purge
}

function main() {
  is_check_build_install_directory "$1" "$2" "build.sh"
  buildpath=$(create_dir "$1")
  installpath=$(create_dir "$2")
  dep_dir=$(get_current_dir)/dependency
  pkg_dir=$(get_current_dir)/pkg
  install_development
  set -e
  install_bisheng "$dep_dir" "$buildpath" "$installpath"
  install_flye "$buildpath" "$installpath" "$pkg_dir" "$(get_current_dir)"
  write_flye_run "$pkg_dir"
  tar_pkg "$pkg_dir"
  echo "# ------------------------------------------------------------------------"
  echo "# 运行软件前请执行以下命令"
  echo -e "\033[1;32;1m# source ""${pkg_dir}""/flye-2.9-hpc/run.sh\033[0m"
  echo "# 来加载Flye运行时环境变量"
  echo "# ------------------------------------------------------------------------"
  rm -rf "$buildpath" "$installpath"
}

main "$@"
